package com.maixy.studyonlineapi.redis.template;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * hash redis 模板
 * Created by jason on 17-3-25.
 */

@Component
public class HashRedisTemplate extends BaseRedisTemplate {

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    public void hset(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    public String hget(String key, String field) {
        return (String)redisTemplate.opsForHash().get(key, field);
    }

    public boolean hexists(String key, String field) {
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    public void hdel(String key, String field) {
        redisTemplate.opsForHash().delete(key, field);
    }

    public Map<String, String> hgetall(String key) {
        Map<String, String> map = new HashMap<>();
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        for (Entry<Object, Object> entry : entries.entrySet()) {
            map.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        return map;
    }

    public void hsetall(String key, Map<String, String> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

}
